package com.hangzhou.xyj.ui.activity;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.manager.PinYinSortManager;
import com.hangzhou.xyj.model.CityModel;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.adapter.CityListAdapter;
import com.hangzhou.xyj.ui.widget.MyLetterListView;
import com.hangzhou.xyj.ui.widget.views.MyRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/1/23.
 */
public class SelectCityActivity extends BaseActivity {
    private MyRecyclerView mRecyclerView;
    private MyLetterListView mLetterLv;//字母索引条
    private PinYinSortManager mSortManager;
    private List<CityModel> mDataList = new ArrayList<>();
    private HashMap<String, Integer> alphaIndexer;//存放存在的汉语拼音首字母和与之对应的列表位置

    @Override
    public void initDatas() {
        String[] str = getResources().getStringArray(R.array.cityies);
        for (String cityName : str) {
            CityModel city = new CityModel();
            city.setName(cityName);
            mDataList.add(city);
        }
        //先进行排序
        sortData();
        mRecyclerView.setAdapter(new CityListAdapter(mContext, mDataList));
    }

    @Override
    public void initTop() {
        enableTitle(true, "选择地区");
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_select_city);
    }

    @Override
    public void initViews() {
        mRecyclerView = findView(R.id.rv_more_city);
        mLetterLv = findView(R.id.lv_more_city);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    public void initListeners() {
        mLetterLv.setOnTouchingLetterChangedListener(new MyLetterListView.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                alphaIndexer = mSortManager.getAlphaIndexer();
                if (alphaIndexer.get(s) != null) {
                    int position = alphaIndexer.get(s);
                    mRecyclerView.scrollToPosition(position);
                    mSortManager.handlerView(position);
                }
            }
        });
    }

    /**
     * 对数据排序
     */
    private void sortData() {
        // 字母排序索引管理器
        mSortManager = new PinYinSortManager(this);
        //进行按字母排序
        List<Object> sortDatas = mSortManager.sortDatas(mDataList, "name");
        mDataList.clear();
        for (Object obj : sortDatas) {
            mDataList.add((CityModel) obj);
        }
    }
}
